import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import * as Icons from '@ant-design/icons-vue';
import { ComponentConfig, DroppedComponent, ComponentGroup } from '@/types/componentTypes';

export const useEditorStore = defineStore('editor', () => {
  // 更改组件属性
  const handleGenderChange = (val: any, options: { attributeType: string, componentType: string }, configType: string) => {
    const component = canvasComponents.value.find(c => c.id === selectedComponentId.value);
    if (component) {
      const configCopy = JSON.parse(JSON.stringify(component.configData.config));
      console.log('当前选中组件的配置:', configCopy);
      if (configType === 'style') {
        let attribute = options.attributeType;
        configCopy['x-component-props'].style[attribute] = val;
      } else if (configType === 'props') {
        configCopy['x-component-props'].propsConfig[options.attributeType] = val;
      }
      console.log('configCopy', configCopy);
      component.configData.config = configCopy;
      saveToHistory();
    }
  };
  // 基础组件列表
  const baseComponents = ref<ComponentConfig[]>([
    {
      id: 'input01',
      label: '输入框',
      field: "Input",
      icon: Icons.FormOutlined,
      config: {
        type: "string",
        title: "输入框",
        "x-decorator": "FormItem",
        "x-component": "Input",
        "x-component-props": {
          placeholder: "请输入",
          allowClear: true,
          style: {
            width: "",
            height:"80px"
          },
          styleConfig: {
            width: {
              type: 'string',
              title: '宽度',
              'x-component': 'Select',
              "x-decorator": "FormItem",
              'x-component-props': {
                options: [
                  { label: '100%', value: '100%' },
                  { label: '50%', value: '50%' },
                  { label: '33.33%', value: '33.33%' },
                  { label: '25%', value: '25%' },
                  { label: '自定义', value: 'custom' }
                ],
                onChange: (e: any) => handleGenderChange(e, { attributeType: "width", componentType: "input01" }, 'style')
              },
              default: '100%'
            },
            height: {
              type: 'number',
              title: '高度',
              'x-component': 'InputNumber',
              "x-decorator": "FormItem",
              'x-component-props': {
                min: 24,
                max: 100,
                step: 1,
                addonAfter: 'px',
                onInput: (e: any) => handleGenderChange(`${e}px`, { attributeType: "height", componentType: "input01" }, 'style')
              },
              default: 32
            },
            margin: {
              type: 'string',
              title: '外边距',
              'x-component': 'Input',
              "x-decorator": "FormItem",
              'x-component-props': {
                placeholder: '请输入外边距，例如：10px 20px 30px 40px',
                addonAfter: 'px',
                onChange: (e: any) => handleGenderChange(e.target.value, { attributeType: "margin", componentType: "input01" }, 'style')
              },
              default: '0px'
            },
            padding: {
              type: 'string',
              title: '内边距',
              'x-component': 'Input',
              "x-decorator": "FormItem",
              'x-component-props': {
                placeholder: '请输入内边距，例如：10px 20px 30px 40px',
                addonAfter: 'px',
                onChange: (e: any) => handleGenderChange(e, { attributeType: "padding", componentType: "input01" }, 'style')
              },
              default: '4px 11px'
            },
            textAlign: {
              type: 'string',
              title: '对齐方式',
              'x-component': 'Radio.Group',
              "x-decorator": "FormItem",
              'x-component-props': {
                optionType: 'button',
                size: 'small',
                options: [
                  { label: '左对齐', value: 'left' },
                  { label: '居中', value: 'center' },
                  { label: '右对齐', value: 'right' }
                ],
                onChange: (e: any) => handleGenderChange(e, { attributeType: "textAlign", componentType: "input01" }, 'style')
              },
              default: 'left'
            },
            background: {
              type: 'string',
              title: '背景色',
              'x-component': 'ColorPicker',
              "x-decorator": "FormItem",
              'x-component-props': {
                format: 'hex',
                onChange: (e: any) => handleGenderChange(e.target.value, { attributeType: "background", componentType: "input01" }, 'style')
              },
              default: '#ffffff'
            }
          },
          propsConfig: {
            placeholder: {
              type: 'string',
              title: '提示文字',
              'x-component': 'Input',
              "x-decorator": "FormItem",
              'x-component-props': {
                placeholder: '请输入提示文字',
                onChange: (e: any) => handleGenderChange(e, { attributeType: "placeholder", componentType: "input01" }, 'props')
              }
            },
            allowClear: {
              type: 'boolean',
              title: '允许清除',
              'x-component': 'Switch',
              "x-decorator": "FormItem",
              default: true,
              'x-component-props': {
                onChange: (e: any) => handleGenderChange(e, { attributeType: "allowClear", componentType: "input01" }, 'props')
              }
            },
            maxLength: {
              type: 'number',
              title: '最大长度',
              'x-component': 'InputNumber',
              "x-decorator": "FormItem",
              'x-component-props': {
                min: 0,
                step: 1,
                onChange: (e: any) => handleGenderChange(e, { attributeType: "maxLength", componentType: "input01" }, 'props')
              }
            },
            disabled: {
              type: 'boolean',
              title: '禁用',
              'x-component': 'Switch',
              "x-decorator": "FormItem",
              default: false,
              'x-component-props': {
                onChange: (e: any) => handleGenderChange(e, { attributeType: "disabled", componentType: "input01" }, 'props')
              }
            }
          }
        }
      }
    },
    {
      id: 'password01',
      label: '密码框',
      field: "Password",
      icon: Icons.LockOutlined,
      config: {
        type: "string",
        title: "密码框",
        "x-decorator": "FormItem",
        "x-component": "Password",
        "x-component-props": {
          placeholder: "请输入密码",
          "x-decorator": "FormItem",
          styleConfig: {
            width: {
              type: 'string',
              title: '宽度',
              'x-component': 'Select',
              "x-decorator": "FormItem",
              'x-component-props': {
                options: [
                  { label: '100%', value: '100%' },
                  { label: '50%', value: '50%' },
                  { label: '33.33%', value: '33.33%' },
                  { label: '25%', value: '25%' },
                  { label: '自定义', value: 'custom' }
                ],
                onChange: (e: any) => handleGenderChange(e, { attributeType: "width", componentType: "password" }, 'style')
              },
              default: '100%'
            },
            height: {
              type: 'number',
              title: '高度',
              'x-component': 'InputNumber',
              "x-decorator": "FormItem",
              'x-component-props': {
                min: 0,
                step: 1,
                placeholder: '请输入高度',
                onChange: (e: any) => handleGenderChange(e, { attributeType: "height", componentType: "password" }, 'style')
              },
              default: 32
            },
            padding: {
              type: 'string',
              title: '内边距',
              'x-component': 'Input',
              "x-decorator": "FormItem",
              'x-component-props': {
                placeholder: '请输入内边距',
                onChange: (e: any) => handleGenderChange(e, { attributeType: "padding", componentType: "password" }, 'style')
              },
              default: '8px'
            }
          }
        }
      }
    },
    {
      id: 'number01',
      label: '数字输入',
      field: "InputNumber",
      icon: Icons.FieldNumberOutlined,
      config: {
        type: "number",
        title: "数字输入",
        "x-decorator": "FormItem",
        "x-component": "InputNumber",
        "x-component-props": {
          placeholder: "请输入数字",
          "x-decorator": "FormItem",
          styleConfig: {
            width: {
              type: 'string',
              title: '宽度',
              'x-component': 'Select',
              "x-decorator": "FormItem",
              'x-component-props': {
                options: [
                  { label: '100%', value: '100%' },
                  { label: '50%', value: '50%' },
                  { label: '33.33%', value: '33.33%' },
                  { label: '25%', value: '25%' },
                  { label: '自定义', value: 'custom' }
                ],
                onChange: (e: any) => handleGenderChange(e, { attributeType: "width", componentType: "number01" }, 'style')
              },
              default: '100%'
            },
            min: {
              type: 'number',
              title: '最小值',
              'x-component': 'InputNumber',
              "x-decorator": "FormItem",
              'x-component-props': {
                onChange: (e: any) => handleGenderChange(e, { attributeType: "min", componentType: "number01" }, 'style')
              },
              default: 0
            },
            max: {
              type: 'number',
              title: '最大值',
              'x-component': 'InputNumber',
              "x-decorator": "FormItem",
              'x-component-props': {
                onChange: (e: any) => handleGenderChange(e, { attributeType: "max", componentType: "number01" }, 'style')
              },
              default: 100
            },
            step: {
              type: 'number',
              title: '步长',
              'x-component': 'InputNumber',
              "x-decorator": "FormItem",
              'x-component-props': {
                onChange: (e: any) => handleGenderChange(e, { attributeType: "step", componentType: "number01" }, 'style')
              },
              default: 1
            }
          }
        }
      }
    }
  ]);

  // 画布中的组件
  const canvasComponents = ref<DroppedComponent[]>([]);

  // 当前选中的组件
  const selectedComponentId = ref<string | null>(null);
  const selectedComponentIds = ref<string[]>([]);
  const draggingId = ref<string | null>(null);
  const groups = ref<ComponentGroup[]>([]);

  // 计算属性：当前选中的组件
  const selectedComponent = computed(() =>
    canvasComponents.value.find(c => c.id === selectedComponentId.value)
  );

  // 添加组件
  const addComponent = (component: ComponentConfig | DroppedComponent, parentId?: string) => {
    let newComponent: DroppedComponent;

    if ('configData' in component) {
      // 如果是拖动已有组件，保留其配置
      newComponent = {
        ...component,
        id: `${component.configData.id}_${Date.now()}`,
        parentId
      };
    } else {
      // 如果是新组件，创建新配置
      newComponent = {
        id: `${component.id}_${Date.now()}`,
        parentId,
        configData: {
          ...component,
          config: {
            ...component.config,
            'x-decorator-props': {
              ...component.config['x-decorator-props'],
            },
            'x-component-props': {
              ...component.config['x-component-props'],
              styleConfig: {
                ...component.config['x-component-props']?.styleConfig
              }
            }
          }
        },
        style: {},
        events: {}
      };
    }

    console.log('Adding new component:', newComponent);
    saveToHistory();
    canvasComponents.value.push(newComponent);
    return newComponent.id;
  };

  // 选择组件
  const selectComponent = (id: string | null) => {
    selectedComponentId.value = id;
    if (id) {
      selectedComponentIds.value = [id];
    } else {
      selectedComponentIds.value = [];
    }
  };

  // 获取选中的组件ID列表
  const getSelectedComponentIds = () => selectedComponentIds.value;

  // 添加到选择
  const addToSelection = (id: string) => {
    if (!selectedComponentIds.value.includes(id)) {
      selectedComponentIds.value.push(id);
    }
  };

  // 从选择中移除
  const removeFromSelection = (id: string) => {
    selectedComponentIds.value = selectedComponentIds.value.filter(cId => cId !== id);
  };

  // 清除选择
  const clearSelection = () => {
    selectedComponentIds.value = [];
    selectedComponentId.value = null;
  };

  // 复制组件
  const duplicateComponent = (id: string) => {
    const component = canvasComponents.value.find(c => c.id === id);
    if (component) {
      const newComponent = JSON.parse(JSON.stringify(component));
      newComponent.id = `${component.configData.id}_${Date.now()}`;
      saveToHistory();
      canvasComponents.value.push(newComponent);
      return newComponent.id;
    }
    return null;
  };

  // 删除组件
  const deleteComponent = (id: string) => {
    const index = canvasComponents.value.findIndex(c => c.id === id);
    if (index > -1) {
      saveToHistory();
      canvasComponents.value.splice(index, 1);
      if (selectedComponentId.value === id) {
        selectComponent(null);
      }
    }
  };

  // 交换组件位置
  const swapComponents = (sourceId: string, targetId: string) => {
    const sourceIndex = canvasComponents.value.findIndex(c => c.id === sourceId);
    const targetIndex = canvasComponents.value.findIndex(c => c.id === targetId);
    if (sourceIndex > -1 && targetIndex > -1) {
      saveToHistory();
      const temp = canvasComponents.value[sourceIndex];
      canvasComponents.value[sourceIndex] = canvasComponents.value[targetIndex];
      canvasComponents.value[targetIndex] = temp;
    }
  };

  // 组件上移
  const moveComponentUp = (id: string) => {
    const index = canvasComponents.value.findIndex(c => c.id === id);
    if (index > 0) {
      saveToHistory();
      const temp = canvasComponents.value[index];
      canvasComponents.value[index] = canvasComponents.value[index - 1];
      canvasComponents.value[index - 1] = temp;
    }
  };

  // 组件下移
  const moveComponentDown = (id: string) => {
    const index = canvasComponents.value.findIndex(c => c.id === id);
    if (index < canvasComponents.value.length - 1) {
      saveToHistory();
      const temp = canvasComponents.value[index];
      canvasComponents.value[index] = canvasComponents.value[index + 1];
      canvasComponents.value[index + 1] = temp;
    }
  };

  // 组件对齐
  const alignComponents = (direction: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom') => {
    if (selectedComponentIds.value.length < 2) return;

    saveToHistory();
    const components = canvasComponents.value.filter(c =>
      selectedComponentIds.value.includes(c.id)
    );
  };

  // 组件成组
  const groupComponents = (componentIds: string[]) => {
    if (componentIds.length < 2) return null;

    const groupId = `group_${Date.now()}`;
    const newGroup: ComponentGroup = {
      id: groupId,
      type: 'group',
      componentIds: [...componentIds]
    };

    saveToHistory();
    groups.value.push(newGroup);
    return groupId;
  };

  // 解组
  const ungroupComponents = (groupId: string) => {
    const index = groups.value.findIndex(g => g.id === groupId);
    if (index > -1) {
      saveToHistory();
      groups.value.splice(index, 1);
    }
  };

  // 复制组
  const duplicateGroup = (groupId: string) => {
    const group = groups.value.find(g => g.id === groupId);
    if (group) {
      const newComponentIds: string[] = [];
      group.componentIds.forEach(id => {
        const newId = duplicateComponent(id);
        if (newId) newComponentIds.push(newId);
      });

      return groupComponents(newComponentIds);
    }
    return null;
  };

  // 删除组
  const deleteGroup = (groupId: string) => {
    const group = groups.value.find(g => g.id === groupId);
    if (group) {
      saveToHistory();
      group.componentIds.forEach(id => deleteComponent(id));
      ungroupComponents(groupId);
    }
  };

  // 历史记录
  const history = ref<DroppedComponent[][]>([]);
  const historyIndex = ref(-1);

  // 保存历史记录
  const saveToHistory = () => {
    history.value = history.value.slice(0, historyIndex.value + 1);
    history.value.push(JSON.parse(JSON.stringify(canvasComponents.value)));
    historyIndex.value++;
  };

  // 撤销
  const undo = () => {
    if (historyIndex.value > 0) {
      historyIndex.value--;
      canvasComponents.value = JSON.parse(
        JSON.stringify(history.value[historyIndex.value])
      );
    }
  };

  // 重做
  const redo = () => {
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++;
      canvasComponents.value = JSON.parse(
        JSON.stringify(history.value[historyIndex.value])
      );
    }
  };

  // 更新组件配置数据
  const updateComponentConfig = (id: string, newConfig: any) => {
    const component = canvasComponents.value.find(c => c.id === id);
    if (component) {
      saveToHistory();
      component.configData.config = { ...component.configData.config, ...newConfig };
    }
  };

  // 更新组件样式
  const updateComponentStyle = (id: string, style: Record<string, string>) => {
    const component = canvasComponents.value.find(c => c.id === id);
    if (component) {
      saveToHistory();
      component.style = { ...component.style, ...style };
    }
  };

  // 更新组件事件
  const updateComponentEvents = (id: string, events: Record<string, string>) => {
    const component = canvasComponents.value.find(c => c.id === id);
    if (component) {
      saveToHistory();
      component.events = { ...component.events, ...events };
    }
  };

  // 设置拖拽ID
  const setDraggingId = (id: string | null) => {
    draggingId.value = id;
  };

  // 更新组件配置的方法
  const updateComponent = (component: DroppedComponent) => {
    const index = canvasComponents.value.findIndex(c => c.id === component.id);
    if (index > -1) {
      // 深拷贝以确保响应式更新
      canvasComponents.value[index] = JSON.parse(JSON.stringify(component));
      // 触发更新
      canvasComponents.value = [...canvasComponents.value];
    }
  };

  // 移动组件
  const moveComponent = (componentId: string, newParentId: string | null) => {
    const component = canvasComponents.value.find(c => c.id === componentId);
    if (component) {
      component.parentId = newParentId;
      // 触发更新
      canvasComponents.value = [...canvasComponents.value];
    }
  };

  return {
    baseComponents,
    canvasComponents,
    selectedComponent,
    selectedComponentId,
    selectedComponentIds,
    draggingId,
    groups,
    addComponent,
    selectComponent,
    getSelectedComponentIds,
    addToSelection,
    removeFromSelection,
    clearSelection,
    updateComponentConfig,
    updateComponentStyle,
    updateComponentEvents,
    undo,
    redo,
    setDraggingId,
    updateComponent,
    moveComponent,
    swapComponents,
    moveComponentUp,
    moveComponentDown,
    alignComponents,
    groupComponents,
    ungroupComponents,
    duplicateGroup,
    deleteGroup,
    duplicateComponent,
    deleteComponent
  };
});